package tech.mobi.child.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import tech.client.utils.FileUtil;
import tech.client.utils.MD5;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {

	private HashMap<String, SoftReference<String>> imageCache;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<String>>();
	}

	public String loadDrawable(final String imageUrl, final File saveDir,
			final ImageCallback imageCallback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<String> softReference = imageCache.get(imageUrl);
			String path = softReference.get();
			if (path != null && !"".equals(path)) {
				return path;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((String) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				String path = cacheImageTC(imageUrl, saveDir);
				imageCache.put(imageUrl, new SoftReference<String>(path));
				Message message = handler.obtainMessage(0, path);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public static String cacheImageTC(String imgPath, File saveDir) {
		String returnPath = "";
		try {
			Log.i("AsyncImageLoader", imgPath);
			String path = imgPath;
			Log.i("img", path);
			File file = new File(saveDir, MD5.getMD5(path)
					+ FileUtil.getExt(path));
			if (file.exists()) {// 判断是否存在缓存图片
				returnPath = file.getPath();
			} else {
				FileOutputStream outStream = new FileOutputStream(file);
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestMethod("GET");
				if (conn.getResponseCode() == 200) {
					InputStream inStream = conn.getInputStream();
					copyStream(inStream, outStream);
					returnPath = file.getPath();
				} else {
					throw new Exception("request image fail");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("AsyncImageLoader", imgPath+"-----"+e.getMessage());
		}
		return returnPath;
	}

	private static void copyStream(InputStream inStream, OutputStream outStream)
			throws Exception {
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
	}

	public interface ImageCallback {
		public void imageLoaded(String path, String imageUrl);
	}

}